package cn.com.generaldata.os.service.indicator_evaluation.coefficient_of_variation;

import java.util.List;

import org.apache.commons.lang3.Validate;
import org.nutz.dao.sql.Criteria;

import cn.com.generaldata.jsme_indicator_system.entity.IndicatorEvaluation;
import cn.com.generaldata.jsme_indicator_system.util.Constants;
import cn.com.generaldata.os.service.indicator_constant.ProvinceIndicatorConstant;
import cn.com.generaldata.os.service.indicator_evaluation.IndicatorEvaluationCalculateService;
import cn.com.generaldata.os.util.BeanMapper;
import cn.com.generaldata.os.vo.IndicatorAccountVO;

import com.google.common.collect.Lists;

/**
 * GOP增长速度变异系数评估指标计算类.
 */
public class GOPGrowthRateVariableCoefficientCalculateService extends IndicatorEvaluationCalculateService {

	private String GOPGrowthRateIndicatorName = ProvinceIndicatorConstant.GOP_GROWTH_RATE_INDICATOR_NAME;

	@Override
	protected Double calculate(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		Double result = null;
		if (indicator.getSection() == Constants.INDICATOR_LEVEL_PROVINCE) {
			result = calculateProvinceResult(indicator, indicatorAccountVO);
		} else if (indicator.getSection() == Constants.INDICATOR_LEVEL_CITY) {
			// 先保留
		}
		return result;

	}

	private Double calculateProvinceResult(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		Double cityGOPGrowthRateSum = 0d;
		List<Double> cityGOPGrowthRates = Lists.newArrayList();
		for (String areaId : ProvinceIndicatorConstant.CITYS) {
			IndicatorAccountVO vo = BeanMapper.map(indicatorAccountVO, IndicatorAccountVO.class);
			vo.setAreaId(areaId);
			Double gopGrowthRate = getCityGOPGrowthRate(vo);
			cityGOPGrowthRateSum += gopGrowthRate;
			cityGOPGrowthRates.add(gopGrowthRate);
		}

		Double avgGOPGrowthRate = cityGOPGrowthRateSum / ProvinceIndicatorConstant.CITYS.length;

		Double d = 0d;
		for (Double gopGrowthRate : cityGOPGrowthRates) {
			d += Math.pow((gopGrowthRate - avgGOPGrowthRate), 2);
		}
		return Math.pow(d / ProvinceIndicatorConstant.CITYS.length, 0.5) / avgGOPGrowthRate;
	}

	/**
	 * 三市海洋生产总值增长速度
	 * 
	 * @param indicatorAccountVO
	 * @return
	 */
	private Double getCityGOPGrowthRate(IndicatorAccountVO indicatorAccountVO) {
		Integer indicatorId = getIndicatorEvaluationId(GOPGrowthRateIndicatorName, indicatorAccountVO.getAreaId());
		Criteria cri = getIndicatorDataCri(indicatorAccountVO, indicatorAccountVO.getYear(), indicatorId);
		Double result = getEvaluationIndicatorValue(cri);
		Validate.isTrue(result != null);
		return result;
	}

}
